const Router = require('koa-router')
const router = new Router({ prefix: '/cjwtxq' })
const u = require('../api')
var pageSize = 10;

router.get('/:id', async (ctx) => {
  let pageNum = 1
  let id = ''
  let idArr = ctx.params.id ? ctx.params.id.split('-') : []
  if (idArr.length > 2) {
    ctx.throw(404)
  }
  idArr.forEach(item => {
    // 问题id
    if (/^\d+$/.exec(item)) {
      id = item
    }
    // 回答分页
    if (/^p\d+$/.exec(item)) {
      pageNum = item.split('p')[1]
    }
    // 验证
    if (!/^\d+$/.exec(item) && !/^p\d+$/.exec(item)) {
      ctx.throw(404)
    }
  })
  // 面包屑
  let crumbsData = [{
    name: '首页',
    href: '/'
  }, {
    name: '常见问题',
    href: '/cjwt'
  }]
  // 获取问题列表
  let getProblem = await u.http({
    url: u.queryQaList,
    params: {
      pageNum,
      pageSize: 15
    }
  })
  // 获取问题详情
  let getProblemInfo = await u.http({
    url: u.queryQaById,
    params: {
      id
    }
  })
  if (getProblemInfo.data) {
    problemInfoData = getProblemInfo.data
    // 追加面包屑
    crumbsData.push({
      name: `${getProblemInfo.data.title.substr(0, 6)}...`,
      href: ''
    })
  } else {
    ctx.throw(404)
  }
  // 获取问题答案
  let getAnswer = await u.http({
    url: u.queryQaAnswerList,
    params: {
      pageNum,
      pageSize,
      qaId: id
    }
  })
  // 修改TDK
  ctx.config.tdk.title = `${getProblemInfo.data.title}-彧胜实业`
  ctx.config.tdk.description = ''
  ctx.config.tdk.keywords = ''

  await ctx.render('cjwtxq.ejs', {
    config: ctx.config,
    crumbsData,
    problemInfoData,
    problemMoreData: getProblem.code == 200 ? getProblem.data.list : [],
    answerData: getAnswer.code == 200 ? getAnswer.data.list : [],
    answerDataTotal: getAnswer.code == 200 ? getAnswer.data.total : 0,
    answerDataPageNum: getAnswer.code == 200 ? getAnswer.data.pageNum : 0,
    answerDataPageSize: pageSize
  })
})

module.exports = router